import re
import sqlite3
import os
import logging
from django.http import HttpResponse
from django.conf import settings
import json
import shutil
oozie_home='/export/datamarket/oozie/oozie-4.3.1/bin/'
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')

def deleteMission(request):

	if request.method == 'POST':
		try:	
			received_json_data=json.loads(request.body.decode().replace("'", "\""))
			logging.info("\n\n\n\t"+str(received_json_data)+"\n\n")
			jobid=received_json_data['jobid'].strip()
			
			db_path = os.path.normpath('/export/datamarket/OozieProperties/oozie_project/db.sqlite3') 
			db = sqlite3.connect(db_path) 
			# 通过cursor创建游标
			cursor = db.cursor()
			sql_jobid="select mission_val from oozie_configuration where jobid ={}".format(jobid)                          
			cursor.execute(sql_jobid) 
			mission_val=cursor.fetchall() 
			mission_val=mission_val[0][0]
			sql_deleteMission="delete from oozie_configuration where jobid={}".format(jobid)                               
			cursor.execute(sql_deleteMission) 
			logging.info("删除sqlite中"+mission_val+"信息") 
			try:
				today='2018-11-10' 
				deleteMissionDir="/export/datamarket/OozieExec/"+today+"/"+mission_val 
				shutil.rmtree(deleteMissionDir) 
				logging.info("删除任务"+mission_val) 
			except:
				pass

			#sql_jobid="select mission_val from oozie_configuration where jobid ={}".format(jobid)
			#cursor.execute(sql_jobid)
			#mission_val=cursor.fetchall()
			#mission_val=mission_val[0][0]
			
			#通过oozie查找要禁用的job的信息
			try:
				os.system(oozie_home+"oozie jobs -localtime -filter 'name={}' -jobtype coordinator -len 1> jobinfo".format(mission_val))
				os.system("sed -i '1d' jobinfo")
				os.system("cat jobinfo |awk -F ' ' '{print$1}' >jobid")
				os.system("sed -i '1d' jobid")
				os.system("sed -i '2d' jobid")
				coordinatorJobid=os.popen("cat jobid").read().strip()
				os.remove("jobinfo")
				os.remove("jobid")
				os.system(oozie_home+"oozie job -kill {}".format(coordinatorJobid))
				cursor.close()
				db.commit()
				db.close()
				result={"result":mission_val+"删除成功","code":"0"} 
				logging.info(result) 
				return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8") 
			except:

				result={"result":mission_val+"删除成功","code":"0"}
				logging.info(result)
				return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
		except:
			result={"result":"oozie中无此任务","code":"1"}
			logging.info(result)
			return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
	else:
		pass
